package com.epfresh.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import com.epfresh.R;
import com.epfresh.adapter.MoreDeliveryTimeAdapter;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.widget.tablayout.SlidingTabLayout;
import com.epfresh.api.widget.tablayout.listener.OnTabSelectListener;
import com.epfresh.bean.DeliveryTime;
import com.epfresh.bean.GoodsParameters;
import com.epfresh.fragment.MarketFragment;
import com.epfresh.global.BaseActivity;
import com.epfresh.views.dialog.MoreMarketDialog;
import com.epfresh.views.dialog.OnFilterClickListener;
import com.epfresh.views.dialog.ProductCategoryDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class HomePreActivity extends BaseActivity  implements OnTabSelectListener {
    private SlidingTabLayout lyTab;
    private ViewPager vp;
    private PagerAdapter pagerAdapter;
    private ImageView ivMore;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pre_home);
        basetitle.setText("预售商品");
        baseback.setVisibility(View.VISIBLE);

        lyTab = (SlidingTabLayout) findViewById(R.id.ly_navigation);
        vp = (ViewPager) findViewById(R.id.vp);
        ivMore = (ImageView) findViewById(R.id.iv_more);
        lyTab.setOnTabSelectListener(this);
        ivMore.setOnClickListener(this);

        ivMore.setVisibility(View.GONE);
        if (pagerAdapter == null) {
            pagerAdapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {
                @Override
                public Fragment getItem(int position) {
                    MarketFragment marketFragment = new MarketFragment();
                    marketFragment.setDeliveryTime(list.get(position).getFormat1());

                    //现售(1)/预售(2)
                    marketFragment.setSaleType("2");
                    //dateSelected = list.get(position).getFormat1();////
                    return marketFragment;
                }

                @Override
                public int getCount() {
                    return list.size();
                }

                @Override
                public int getItemPosition(Object object) {
                    return POSITION_NONE;
                }

            };
        }
        vp.setAdapter(pagerAdapter);
        requestOrderList();
    }


    @Override
    public void onTabSelect(int i) {

        if (pop != null && pop.isShowing()) {
//            adapter.setCurrentIndex(i-1);
//            adapter.notifyDataSetChanged();
            pop.dismiss();
        }
    }

    @Override
    public void onTabReselect(int i) {

    }




    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_more:
                Intent intent = new Intent(this, CalendarPreActivity.class);
                int position = vp.getCurrentItem();
                intent.putExtra("position",position);
                intent.putExtra("timeStringList",timeStringList);
                startActivityForResult(intent,0x001);

                //openMoreMarket();
                break;
            case R.id.baseback:
                finish();
                break;
        }
    }

    ArrayList<String> timeStringList;

    public MoreMarketDialog pop;
    MoreDeliveryTimeAdapter adapter;
    private void openMoreMarket() {

        if (pop == null) {
            pop = new MoreMarketDialog(this);
            GridView gv = (GridView) pop.findViewById(R.id.gv_more);
            gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    lyTab.setCurrentTab(i );
                    pop.dismiss();
                }
            });
            adapter = new MoreDeliveryTimeAdapter(this, list);
            gv.setAdapter(adapter);

        }
        adapter.setCurrentIndex(lyTab.getCurrentTab() );
        if (pop.isShowing()) {
            pop.dismiss();
        } else {
//            vLine.setVisibility(View.VISIBLE);
            pop.show();
            adapter.notifyDataSetChanged();
        }
    }

    List<DeliveryTime> list = new ArrayList<>();

    public void loadView() {
        //加载title
        String[] titles = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            titles[i] = list.get(i).getFormat2()+"";
        }
        if (list.size() > 0) {
            ivMore.setVisibility(View.VISIBLE);
        }else {
            ivMore.setVisibility(View.GONE);
        }
//        lyTab.setTitles(titles);
        if(titles==null||titles.length==0){
            setContentView(R.layout.empty_goods);
            return;
        }
        lyTab.setViewPager(vp, titles);
        pagerAdapter.notifyDataSetChanged();
    }


    public void requestOrderList() {

        RequestEntityPurchase<Map<String, String>> entity = new RequestEntityPurchase<>();
        Map<String, String> map = new HashMap<>();
        entity.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_product_getDeliveryTimes);
        entity.setParameters(map);

        request(entity, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_product_getDeliveryTimes, onRequestListener);
    }


    OnRequestListener<List<DeliveryTime>> onRequestListener = new OnRequestListener<List<DeliveryTime>>() {
        @Override
        public List<DeliveryTime> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<List<DeliveryTime>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            setContentView(R.layout.error_view);
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            setContentView(R.layout.error_view);
        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<List<DeliveryTime>> response, Object tag) {
            showMainView();
            List<DeliveryTime> orderResponse = response.getResponseElement();
            list.addAll(orderResponse);

            timeStringList =  new ArrayList<>() ;
            for(int i=0;i<list.size();i++){
                timeStringList.add(list.get(i).getFormat1());
            }

            loadView();
            pagerAdapter.notifyDataSetChanged();
        }
    };





    ProductCategoryDialog productCategoryDialog;

    public void openProductCategory(String marketId, GoodsParameters parameters, OnFilterClickListener onFilterClickListener) {

        if (productCategoryDialog == null) {
            productCategoryDialog = new ProductCategoryDialog(this);
        }
        productCategoryDialog.setMarketId(marketId);
        productCategoryDialog.setParameters(parameters);
        productCategoryDialog.setOnFilterClickListener(onFilterClickListener);
        productCategoryDialog.show();
        productCategoryDialog.updateCategory();
    }


    @Override
    public void onBackPressed() {

        if (productCategoryDialog != null && productCategoryDialog.isShowing()) {
            productCategoryDialog.dismiss();
            return;
        }

        super.onBackPressed();
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == 0x001) {
            if (data != null) {
                int position = data.getIntExtra("position",0);
                lyTab.setCurrentTab(position);
            }
        }
    }




}
